var Bill = function () {
    return Bill.fn.init();
}

// Declare
Bill.fn = Bill.prototype = {


	payment:null,
	proOptions:null,
	index:1,

	// Init
    init:function() {

    	// Khoi tao doi pay mayment
    	var obj = $('#payment');
    	this.payment = {
    		deposit: obj.find('#BillGetPayment'),
    		sum: obj.find('#BillSum'),
    		discount: obj.find('#BillDiscount'),
    		remaining: obj.find('#BillRemaining')
    	};

    	// Khoi tao autocomplete
    	var input = $('#find');
    	this.proOptions = {
    		tmplPath:'auto',
    		tmplName:'product',
    		input:input,
    		content:input.next(),
    		update: $('.tbproduct tbody'),
    		url:'/products/search'
    	};

    	this.autocomplete(this.proOptions);
    },

    /**
	 * Auto comleted
	 *
	 * @param:
	 */
    productAuto:null,
    autocomplete: function(options)
    {
    	if(this.productAuto === null) {
    		this.productAuto = new Autocomplete();
    	}

    	this.productAuto.setup(options);
    	this.productAuto.selected = this.selectedPro;
    	this.productAuto.parent = this;
    },

	/**
	 * Selected
	 *
	 * @param:
	 */
	selectedPro:function(event) {
		var _this = this;

		// Xoa errors
		_this.input.parent().find('.error-message').remove();

		// Neu _this nay la cua auto thi chuyen lai this cua bill
		if( _this.parent ) _this = _this.parent;

		var obj = $(event.currentTarget);

		var id = obj.attr('id');

		var json = {
			idx:_this.index,
			id:id,
			name:obj.html(),
			price: formatMoney(parseFloat(obj.attr('price')))
		};

		$.when(template.load('selected-product', '')).then(function(tpml){

			var html = $(template.render(tpml, json));

			html.find('input').each( function (){
		        var name = $(this).attr('name');
		        name = name.replace('[DetailBill]', '[DetailBill][' + _this.index + ']');

		        $(this).attr('name', name );
		    });

			_this.productAuto.update.append(html);

			_this.index++;
		});

		// remove li da chon
	    obj.remove();

		// Bind event close khi click ra ngoai
	    _this.productAuto.closeStart();

		_this.setPrice();
	},

	/**
	 * Remove selected
	 *
	 * @param:
	 */
	removeSelected: function(obj) {
		if(obj) {
			var id = obj.attr('pid');
			var datanone = this.productAuto.input.attr('data-none');
			datanone = datanone.replace(id + ',', '');
			this.productAuto.input.attr('data-none', datanone);
			obj.closest('tr').remove();

			this.setPrice();
			return true;
		}
		return false;
	},

	/**
	 * Set Price
	 *
	 * @param:
	 */
	setPrice:function() {
		var _this = this;
		var sum = 0;
		var remaining = 0;

		// Tinh sum product
		var product = this.proOptions.update.find('tr');
		if(product.length > 0)
		{
			product.each(function(idx, val){
				var obj = $(this);
				obj.find('.stt').html(idx + 1);

				var price = obj.find('.price').html();
				price = price.replaceAll( ['.', ',', ' '], '');
				if(!isNumeric(price)) price = 1;

				var $amount = obj.find('.amount');
				var amount = $amount.val().replaceAll( ['.', ',', ' '], '');

				if( !isNumeric(amount)) {
					amount = parseFloat(amount);
					if(!isNumeric(amount)){
						amount = 1;
					}
				}

				$amount.val(amount).attr('value', amount);

				sum += parseInt(price) * parseInt( amount );
			});
		}

		// tinh giam gia
		var deposit = (this.payment.deposit.val()).replaceAll( ['.', ',', ' '], '');
		var discount = (this.payment.discount.val()).replaceAll( ['.', ',', ' '], '');

		if( !isNumeric(deposit)) {
			deposit = parseFloat(deposit);
			if( !isNumeric(deposit)) {
				deposit = 0;
			}
		}
		deposit = parseInt(deposit);


		if( !isNumeric(discount)) {
			discount = parseFloat(discount);
			if( !isNumeric(discount)) {
				discount = 0;
			}
		}

		discount = parseInt(discount);

		discount = discount < 0 ? 0 : ( discount > 100 ? 100 : discount);

		remaining = sum - (( sum * discount )/100 + deposit);

		// Truong hop remaining < 0
		if( remaining < 0 )
		{
			remaining = 0;
			deposit = sum - (( sum * discount )/100);

			if(deposit < 0) deposit = 0;
		}

		// show payment
		this.payment.deposit.val(deposit).attr('value', formatMoney(deposit));
		this.payment.discount.val(discount).attr('value', discount);
		this.payment.sum.val(sum).attr('value', formatMoney(sum));
		this.payment.remaining.val(remaining).attr('value', formatMoney(remaining));
	},

	test: function($modal)
	{

		// create the backdrop and wait for next modal to be triggered
		//$('body').modalmanager('loading');
//		$modal.modal({
//			  keyboard: false
//		});

//		var url = '/homes/loadJsTemplate/product/auto';

		$.when(
			template.load('test', 'auto')
		).then(function(tmp){
			var html = template.render( tmp, {id:'hello', msg:'thanh cong roi'} );
			$modal.before(html);
		});

		//var tmp = template.render("<h3>{{id}}</h3><p>{{msg}}</p>", {id:'hello', msg:'thanh cong roi'});
//		$modal.before(tmp);

	}
}

var bill = new Bill();

